package com.finger.orderservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finger.commonutil.exception.YyghException;
import com.finger.modelservice.enums.OrderStatusEnum;
import com.finger.modelservice.enums.PaymentStatusEnum;
import com.finger.modelservice.enums.PaymentTypeEnum;
import com.finger.modelservice.model.order.OrderInfo;
import com.finger.modelservice.model.order.PaymentInfo;
import com.finger.modelservice.result.ResultCodeEnum;
import com.finger.modelservice.vo.order.SignInfoVo;
import com.finger.orderservice.client.HospClient;
import com.finger.orderservice.mapper.PaymentInfoMapper;
import com.finger.orderservice.service.OrderInfoService;
import com.finger.orderservice.service.PaymentInfoService;
import com.finger.serviceutil.helper.HttpRequestHelper;
import com.finger.serviceutil.util.MD5;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private HospClient hospClient;
    // 保存支付记录
    @Override
    public void savePaymentInfo(OrderInfo orderInfo, Integer status) {

        Integer resultCount = baseMapper.selectCount(new QueryWrapper<PaymentInfo>().eq("order_id", orderInfo.getId()).eq("payment_type",status));

        if(resultCount>0) return;

        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setGmtCreate(new Date());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(status);
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")+"|"+orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle();
        paymentInfo.setSubject(subject);
        paymentInfo.setTotalAmount(orderInfo.getAmount());
        baseMapper.insert(paymentInfo);

    }

    @Override
    public void paySuccess(Map map) {

        // 更新订单信息
        String outTradeNo = (String) map.get("out_trade_no");
        OrderInfo orderInfo = orderInfoService.getOne(new QueryWrapper<OrderInfo>().eq("out_trade_no", outTradeNo));
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderInfoService.updateById(orderInfo);
        // 更新支付信息
        String orderId = orderInfo.getId();
        PaymentInfo paymentInfo = paymentInfoService.getOne(new QueryWrapper<PaymentInfo>().eq("out_trade_no", outTradeNo).eq("payment_type", PaymentTypeEnum.WEIXIN.getStatus()));
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setTradeNo((String) map.get("transaction_id"));
        paymentInfo.setCallbackContent(map.toString());
        paymentInfoService.updateById(paymentInfo);

        // 更新远程医院订单信息
        SignInfoVo signInfoVo
                = hospClient.findSignInfoVO(orderInfo.getHoscode());
        if (null == signInfoVo) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", orderInfo.getHoscode());
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = MD5.encrypt(signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl() + "/order/updatePayStatus");
        if (result.getInteger("code") != 200) {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
    }
}
